package framework.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.net.URI;
import java.util.Base64;

@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "sys.storage.http")
public class FileStorageHttpConfig implements InitializingBean {

    /**
     * 名称
     */
    private String name;
    /**
     * 服务器地址，例：http://example.com/file/, 结尾必须带 /
     */
    private String address;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 认证头
     */
    private String authorization;
    /**
     * 启用压缩的路径前缀
     */
    private String[] compressPathStarts;
    /**
     * 管理路径名, 路径中的第1个片段
     */
    private String[] managers;
    /**
     * 链接超时时间(毫秒)
     */
    private Integer connectTimeout = 6000;
    /**
     * 读取超时时间(毫秒)
     */
    private Integer readTimeout = 30000;

    public void setAddress(String address) {
        if (StringUtils.isBlank(address))
            return;
        if (address.endsWith("/")) {
            //
        } else if (address.endsWith("\\")) {
            address = address.substring(0, address.length() - 1) + "/";
        } else {
            address += "/";
        }
        this.address = address;
    }

    public String url(String path) {
        if (path.charAt(0) == '/')
            return address + path.substring(1);
        return address + path;
    }

    public URI uri(String path) {
        return URI.create(url(path));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (StringUtils.isBlank(getAuthorization())) {
            if (StringUtils.isNotBlank(getUsername()) && StringUtils.isNotBlank(getPassword())) {
                this.authorization = "Basic " + Base64.getEncoder()
                        .encodeToString((username + ":" + password).getBytes());
            }
        }
    }
}
